package com.tanhua.manage.service;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.manage.mapper.AdminMapper;
import com.tanhua.manage.pojo.Admin;
import com.tanhua.manage.util.UserThreadLocal;
import com.tanhua.manage.vo.AdminVo;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class AdminService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    //验证码的key
    private static final String CHECK_CODE_KEY = "CHECK_CODE_KEY_";

    //token的key
    private static final String TOKEN_KEY = "TOKEN_KEY_";

    @Value("${jwt.secret}")
    private String secret;

    @Autowired
    private AdminMapper adminMapper;



    public void saveVerification(String uuid,String code) {
        //将验证码存入redis,设置有效时间为3分钟
        String key= CHECK_CODE_KEY + uuid;
        this.redisTemplate.opsForValue().set(key,code, Duration.ofMinutes(3));
    }

    /**
     * @param username
     * @param password
     * @param code
     * @param uuid
     * @return
     */
    public String login(String username, String password, String code, String uuid) {

        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        Admin admin = this.adminMapper.selectOne(queryWrapper);
        if (null == admin) {
            return null;
        }
        String pwd = DigestUtils.md5Hex(password);

        if (!StringUtils.equals(pwd, admin.getPassword())) {
            return null;
        }

        String redisKey = CHECK_CODE_KEY + uuid;

        String value = this.redisTemplate.opsForValue().get(redisKey);
        if (StringUtils.isEmpty(value)) {
            return null;
        }
        if (!StringUtils.equalsIgnoreCase(value, code)) {
            // 如果从redis中取出的验证码与用户输入的不一致，验证码输入错误
            return null;
        }

        // 验证码正确,删除之前的验证码
        this.redisTemplate.delete(redisKey);


        // 将账号和用户id封装成map集合，然后生成token
        Map<String, Object> claims = new HashMap<String, Object>();
        claims.put("id", admin.getId());

        // 生成token
        String token = Jwts.builder()
                //payload，存放数据的位置，不能放置敏感数据，如：密码等
                .setClaims(claims)
                //设置加密方法和加密盐
                .signWith(SignatureAlgorithm.HS256, secret)
                //设置过期时间，12小时后过期
                .setExpiration(new DateTime().plusHours(12).toDate())
                .compact();
        //System.out.println(token);
        String tokenkey = TOKEN_KEY + admin.getId();
        this.redisTemplate.opsForValue().set(tokenkey, token);
        return token;
    }

    /**
     * 用户基本信息
     *
     * @return
     */
    public AdminVo queryAdminByToken() {
        try {


            Admin admin  = UserThreadLocal.get();

            AdminVo adminVo = new AdminVo();
            adminVo.setUid(String.valueOf(admin.getId()));
            adminVo.setUsername(admin.getUsername());
            adminVo.setAvatar(admin.getAvatar());
            return adminVo;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public boolean removeToken(String token){
        token = token.substring(7, token.length());
        // 通过token解析数据
        Map<String, Object> body = Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody();

        Admin admin  = this.adminMapper.selectById(Long.valueOf(body.get("id").toString()));

        String tokenkey = TOKEN_KEY + admin.getId();
        return this.redisTemplate.delete(tokenkey);
    }

    public Admin findByToken(String token) {
        token = token.substring(7, token.length());
        //System.out.println("parse:" + token);
        // 通过token解析数据
        Map<String, Object> body = Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody();

        Admin admin  = this.adminMapper.selectById(Long.valueOf(body.get("id").toString()));
        //System.out.println(admin);
        return admin;
    }
}
